<template>
  <div class="lyric" ref="wrap" @touchstart="start" @touchend='end'>
    <ul class="words">
      <li
        v-for="(item, index) in lyric"
        :key="index"
        :class="{ active: index == currentLyric }"
        ref="list"
      >
        <span class="ly" @click.stop="lyClick(item)">
          {{ item.word }}
        </span>
      </li>
    </ul>
  </div>
</template>

<script>
import $ from "jquery";
import { mapState, mapGetters } from "vuex";
export default {
  data() {
    return {
      bool: false,
    };
  },
  computed: {
    ...mapState({
      lyric: (state) => state.player.lyrics,
      duration: (state) => state.player.duration,
    }),
    ...mapGetters({
      currentLyric: "player/currentLyric",
    }),
  },
  watch: {
    currentLyric(newVal) {
      if (this.bool) return;
      this.lyricScroll(newVal);
    },
  },
  methods: {
    // 歌词滚动事件
    lyricScroll(newVal) {
      let currentHeight = $(".active").height() * (newVal + 1); //当前滚动高度
      let height = $(this.$refs.wrap).height() / 2; //盒子总高度
      let lyheight = $(".active").height(); //歌词高度
      if (currentHeight > height) {
        let offset = lyheight * (newVal - ~~(height / lyheight)); //正确的偏移量
        $(this.$refs.wrap).animate({ scrollTop: offset }, 300);
      } else {
        $(this.$refs.wrap).animate({ scrollTop: 0 }, 300);
      }
    },
    // 点击跳转到歌词播放
    lyClick(item) {
      this.$store.commit("player/setProgress", item.time / this.duration);
      this.bus.$emit("setCurrentTime");
    },
    // 歌词滚动时
    start() {
      this.bool = true;
    },
    end(){
      this.bool=false
    }
  }
};
</script>
 
<style lang = "scss" scoped>
@import "@/assets/global-style.scss";
.lyric {
  position: relative;
  height: 100%;
  overflow: auto;
  transition: all 0.5s;
  .words {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    transition: all 0.5s;
    li {
      text-align: center;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color:#fff;
    }
    li.active {
      color: #1ecc94;
    }
  }
}
/* 歌词显示部分 */
.ly {
  display: inline-block;
  height: 100%;
}
</style>